﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Restful_Api.Entities;
using Restful_Api.Helpers;
using Restful_Api.Models;
using Restful_Api.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Restful_Api.Controllers
{
    /// <summary>
    /// 操作一组公司
    /// </summary>
    [ApiController]
    [Route("api/CompanyCollections")]
    public class CompanyCollectionsController : ControllerBase
    {
        private readonly IMapper mapper;
        private readonly ICompanyRepository companyRepository;

        public CompanyCollectionsController(IMapper mapper, ICompanyRepository companyRepository)
        {
            this.mapper = mapper;
            this.companyRepository = companyRepository;
        }
        [HttpGet("{ids}",Name =nameof(GetCompanyCollection))]
        public async Task<IActionResult> GetCompanyCollection(
            [FromRoute]
            //id1,id2,id3这个例子是这种类型传递的 ArrayModelBinder通过我们自定义的解析并且赋值到ids
            [ModelBinder(binderType:typeof(ArrayModelBinder))]
             IEnumerable<Guid> ids)
        {
            if (ids == null)
                return BadRequest();

            var entities = await companyRepository.GetCompaniesAsync(ids);
            if (ids.Count() != entities.Count())
                return NotFound();

            var dtoToReturn = mapper.Map<IEnumerable<CompanyDto>>(entities);
            return Ok(dtoToReturn);
        }
        [HttpPost]
        public async Task<ActionResult<IEnumerable<CompanyDto>>> CreateCompanyCollection(IEnumerable<CompanyAddDto> companyDtos)
        {
            var companyEntities = mapper.Map<IEnumerable<Company>>(companyDtos);
            foreach (var item in companyEntities)
            {
                companyRepository.AddCompany(item);
            }
            await companyRepository.SaveAsync();

            var dtos = mapper.Map<IEnumerable<CompanyDto>>(companyEntities);

            //把每项的id 拼接起来作为参数传递
            var ids = string.Join(",", dtos.Select(x => x.Id));

            //CreatedAtRoute会生成 能找到这组资源的url
            return CreatedAtRoute(nameof(GetCompanyCollection), new { ids }, dtos);
        }
    }
}
